package com.crm.crm.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.crm.domain.Dept;
import com.crm.crm.domain.SysMenu;
import com.crm.crm.domain.vo.TreeSelectVo;
import com.crm.crm.domain.vo.business.DeptNode;
import com.crm.crm.mapper.SystemMapper;
import com.crm.crm.service.SystemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class SystemServiceImpl extends ServiceImpl<SystemMapper, SysMenu> implements SystemService {
    @Autowired
    private SystemMapper systemMapper;
    @Override
    public List<TreeSelectVo> findMenuTreeSelect() {

        log.info("获取菜单树,Service实现类开始运行");
        // 获取所有menu
        List<SysMenu> list = systemMapper.list();
        log.info("数据库查询结果是" + list);
        return buildMenuTree(list);
    }

    /**
     * 构建菜单树（支持任意层级）
     */
    private List<TreeSelectVo> buildMenuTree(List<SysMenu> depts) {
        log.info("开始构建部门树");
        Map<Long, TreeSelectVo> nodeMap = new HashMap<>();
        List<TreeSelectVo> rootNodes = new ArrayList<>();
        log.info("开始初始化节点");
        // 初始化所有节点
        for (SysMenu menu : depts) {
            TreeSelectVo node = new TreeSelectVo();
            node.setId(menu.getMenuId());
            node.setLabel(menu.getMenuName());
            node.setChildren(new ArrayList<>());
            nodeMap.put(node.getId(), node);
        }
        log.info("建立父子关系");
        // 建立父子关系
        for (SysMenu menu : depts) {
            TreeSelectVo node = nodeMap.get(menu.getMenuId());
            if (menu.getParentId() == null || menu.getParentId() == 0) {
                rootNodes.add(node); // 根节点
            } else {
                TreeSelectVo parentNode = nodeMap.get(menu.getParentId());
                if (parentNode != null) {
                    parentNode.getChildren().add(node);
                }
            }
        }

        log.info("对每个节点的 children 按照 id 排序");
        // 对每个节点的 children 按照 id 排序（可选）
        rootNodes.sort(Comparator.comparing(TreeSelectVo::getId));
        sortChildrenRecursively(rootNodes);

        log.info("返回结果");
        return rootNodes;
    }
    private void sortChildrenRecursively(List<TreeSelectVo> nodes) {
        for (TreeSelectVo node : nodes) {
            if (node.getChildren() != null && !node.getChildren().isEmpty()) {
                node.getChildren().sort(Comparator.comparing(TreeSelectVo::getId));
                sortChildrenRecursively(node.getChildren());
            }
        }
    }
}
